package dal

import (
	"errors"
)

// ConsultSituation 咨询情况 ,单个学生记录表单用多表查询方式
type ConsultSituation struct {
	Recordid          int64  `gorm:"primaryKey;not null" json:"recordid"` //自动增长，每次插入永不重复
	StudentNum        string `gorm:"type:varchar(10)" json:"studentNum"`
	MainComplaint     string `gorm:"" json:"main_complaint"`
	Problem           string `gorm:"" json:"problem"`
	Experience        string `gorm:"" json:"experience"`
	FamilyHistory     string `gorm:"" json:"family_history"`
	MentalState       string `gorm:"" json:"mental_state"`
	DangerEstimate    string `gorm:"" json:"danger_estimate"`
	ConsultProblem    string `gorm:"" json:"consult_problem"`
	CrisisInterfere   string `gorm:"" json:"crisis_interfere"`
	MentalObstacle    string `gorm:"" json:"mental_obstacle"`
	RelationInfo      string `gorm:"" json:"relation_info"`
	ConsultTime       string `gorm:"" json:"consult_time"`
	ConsultState      int64  `gorm:"default 0" json:"consult_state"`
	ConsultantName    string `gorm:"" json:"consultant_name"` //咨询师
	ConsultantAccount string `gorm:"" json:"consultant_account"`
	StartTime         string `gorm:"type:datetime" json:"start_time"`
	EndTime           string `gorm:"type:datetime" json:"end_time"`
	ConsultContent    string `gorm:"" json:"consult_content"`
	HandleAdvice      string `gorm:"" json:"handle_advice"`
	IsDelete          int64  `gorm:"default 0"` //0表示未删除，1表示已删除
}

// StudentConsultRecord 学生咨询记录表单结构
type StudentConsultRecord struct {
	Recordid     int64  `json:"recordid"`
	StudentNum   string `json:"studentNum"`
	Name         string `json:"name"`
	Gender       string `json:"gender"`
	Organization string `json:"organization"`
	StartTime    string `json:"consulttime"` //startTime
	HandleAdvice string `json:"handleadvice"`
	ConsultState int64  `json:"ended"`      //是否结案（1已结案，0未结案）
	EndTime      string `json:"committime"` //endTime
	ConsultTime  string `json:"consultans"` //ConsultTime 咨询次数
}

func (s *ConsultSituation) Create(c *ConsultSituation) (ConsultSituation, error) {
	return *c, DB.Create(c).Error
}

// GetStudentConsultRecord 获取学生咨询记录表单
func (s *ConsultSituation) GetStudentConsultRecord(page int64, pagesize int64) ([]StudentConsultRecord, error) {
	var studentConsultRecord []StudentConsultRecord
	err := DB.Raw("SELECT recordid,student_num,name,gender,organization,start_time,handle_advice,"+
		"consult_state,end_time,consult_time FROM consult_situations NATURAL JOIN consult_student_infos"+
		" WHERE is_delete = 0 ORDER BY recordid ASC LIMIT ? OFFSET ?", pagesize, (page-1)*pagesize).Scan(&studentConsultRecord).Error
	return studentConsultRecord, err
}

func (s *ConsultSituation) DeleteStudentConsultRecord(recordID int64) error {
	var consultSituation ConsultSituation
	//查找是否存在
	err := DB.Where("recordid = ?", recordID).Find(&consultSituation).Error
	if err != nil {
		return errors.New("该咨询记录不存在")
	}
	//删除操作
	consultSituation.IsDelete = 1

	return DB.Save(&consultSituation).Error
}

func (s *ConsultSituation) EditStudentConsultRecord(d *StudentConsultRecord) error {
	//recordid是否存在
	var consultSituation ConsultSituation
	if err := DB.Where("recordid = ? AND is_delete = ?", d.Recordid, 0).First(&consultSituation).Error; err != nil {
		return errors.New("该咨询记录不存在")
	}
	var conStudentInfo ConsultStudentInfo
	err := DB.Raw("SELECT * FROM consult_student_infos WHERE student_num = ?", d.StudentNum).Scan(&conStudentInfo).Error
	if err != nil {
		return errors.New("该学号不存在")
	}
	//Update 姓名性别组织
	if d.Name != "" {
		err = DB.Exec("UPDATE consult_student_infos SET name = ? WHERE student_num = ?", d.Name, d.StudentNum).Error
		if err != nil {
			return err
		}
	}
	if d.Gender != "" {
		err = DB.Exec("UPDATE consult_student_infos SET gender = ? WHERE student_num = ?", d.Gender, d.StudentNum).Error
		if err != nil {
			return err
		}
	}
	if d.Organization != "" {
		err = DB.Exec("UPDATE consult_student_infos SET organization = ? WHERE student_num = ?", d.Organization, d.StudentNum).Error
		if err != nil {
			return err
		}
	}
	//Update其他信息
	consultSituation.StudentNum = d.StudentNum
	if d.StartTime != "" {
		consultSituation.StartTime = d.StartTime
	}
	if d.HandleAdvice != "" {
		consultSituation.HandleAdvice = d.HandleAdvice
	}

	consultSituation.ConsultState = d.ConsultState

	if d.EndTime != "" {
		consultSituation.EndTime = d.EndTime
	}
	if d.ConsultTime != "" {
		consultSituation.ConsultTime = d.ConsultTime
	}
	return DB.Save(&consultSituation).Error
}

func (s *ConsultSituation) AddStudentConsultRecord(d *StudentConsultRecord) error {
	var conStudentInfo ConsultStudentInfo
	var conSituation ConsultSituation
	err := DB.Where("recordid = ?", d.Recordid).First(&conSituation).Error
	if err == nil {
		//"该咨询记录已经存在"
		//未被删除
		if conSituation.IsDelete == 0 {
			return errors.New("该咨询记录已经存在")
		} else { //已被删除，则删除后重新插入
			err = DB.Delete(&conSituation).Error
			if err != nil {
				return err
			}
		}
	}
	err = DB.Raw("SELECT * FROM consult_student_infos WHERE student_num = ?", d.StudentNum).Scan(&conStudentInfo).Error
	//学号不存在,插入该信息
	if conStudentInfo.StudentNum == "" {
		//return errors.New("该学号不存在")
		err = DB.Exec("INSERT INTO consult_student_infos "+
			"values (?,?,?,\"\",?,\"\",\"\",\"\")", d.StudentNum, d.Name, d.Gender, d.Organization).Error
		if err != nil {
			return err
		}
	} else { //学号存在，修改对应信息
		if d.Name != "" {
			err = DB.Exec("UPDATE consult_student_infos SET name = ? WHERE student_num = ?", d.Name, d.StudentNum).Error
			if err != nil {
				return err
			}
		}
		if d.Gender != "" {
			err = DB.Exec("UPDATE consult_student_infos SET gender = ? WHERE student_num = ?", d.Gender, d.StudentNum).Error
			if err != nil {
				return err
			}
		}
		if d.Organization != "" {
			err = DB.Exec("UPDATE consult_student_infos SET organization = ? WHERE student_num = ?", d.Organization, d.StudentNum).Error
			if err != nil {
				return err
			}
		}
	}
	//创建一个新的数据插入到ConsultSituation中
	var consultSituation ConsultSituation
	consultSituation.Recordid = d.Recordid
	consultSituation.StudentNum = d.StudentNum
	consultSituation.StartTime = d.StartTime
	consultSituation.HandleAdvice = d.HandleAdvice
	consultSituation.ConsultState = d.ConsultState
	consultSituation.EndTime = d.EndTime
	consultSituation.ConsultTime = d.ConsultTime
	conSituation.IsDelete = 0
	return DB.Create(&consultSituation).Error
}

func (s *ConsultSituation) GetStudentConsultRecordByPara(ParaArray []int, checkVar StudentConsultRecord, page int64, pagesize int64) ([]StudentConsultRecord, error) {
	var studentConsultRecord []StudentConsultRecord
	sqlState := "SELECT recordid,student_num,name,gender,organization,start_time,handle_advice," +
		"consult_state,end_time,consult_time FROM consult_situations NATURAL JOIN consult_student_infos WHERE is_delete = 0"
	//增加Where语句
	if ParaArray[0] == 1 {
		sqlState += " AND"
		sqlState += " student_num = \"" + checkVar.StudentNum + "\""
	}
	if ParaArray[1] == 1 {
		sqlState += " AND"
		sqlState += " name = \"" + checkVar.Name + "\""
	}
	if ParaArray[2] == 1 {
		sqlState += " AND"
		sqlState += " gender = \"" + checkVar.Gender + "\""
	}
	if ParaArray[3] == 1 {
		sqlState += " AND"
		sqlState += " organization = \"" + checkVar.Organization + "\""
	}
	if ParaArray[4] == 1 {
		sqlState += " AND"
		sqlState += " handle_advice = \"" + checkVar.HandleAdvice + "\""
	}
	if ParaArray[5] == 1 {
		sqlState += " AND"
		if checkVar.ConsultState == 1 {
			sqlState += " consult_state = 1"
		} else {
			sqlState += " consult_state = 0"
		}
	}
	if ParaArray[6] == 1 {
		sqlState += " AND start_time >= \"" + checkVar.StartTime + "\" AND end_time <= \"" + checkVar.EndTime + "\""
	}
	sqlState += " LIMIT ? OFFSET ?"
	err := DB.Raw(sqlState, pagesize, (page-1)*pagesize).Scan(&studentConsultRecord).Error
	return studentConsultRecord, err
}

// ReopenConsultSituation 重新开启单个咨询记录
func (s *ConsultSituation) ReopenConsultSituation(recordid int64) (int64, error) {
	var consultSituation ConsultSituation
	err := DB.Where("recordid = ? AND is_delete = 0", recordid).Find(&consultSituation).Error
	if err != nil {
		return 0, errors.New("该咨询记录不存在")
	}
	//Set null for all attrbutes except recordid and consultstate
	consultSituation.StudentNum = ""
	consultSituation.MainComplaint = ""
	consultSituation.Problem = ""
	consultSituation.Experience = ""
	consultSituation.FamilyHistory = ""
	consultSituation.MentalState = ""
	consultSituation.DangerEstimate = ""
	consultSituation.ConsultProblem = ""
	consultSituation.CrisisInterfere = ""
	consultSituation.MentalObstacle = ""
	consultSituation.RelationInfo = ""
	consultSituation.ConsultTime = ""
	consultSituation.ConsultantName = ""
	consultSituation.ConsultantAccount = ""
	consultSituation.ConsultContent = ""
	consultSituation.HandleAdvice = ""
	consultState := consultSituation.ConsultState
	err = DB.Save(&consultSituation).Error
	if err != nil {
		return 0, err
	}
	//日期型数据只能设置为NULL，不能设置为""
	err = DB.Exec(" UPDATE consult_situations SET start_time=null,end_time=null").Error
	if err != nil {
		return 0, err
	}
	return consultState, err
}

func (s *ConsultSituation) GiveEnd(recordid int64) (int64, error) {
	var consultSituation ConsultSituation
	err := DB.Where("recordid = ? AND is_delete = 0", recordid).Find(&consultSituation).Error
	if err != nil {
		return 0, errors.New("该咨询记录不存在")
	}
	if consultSituation.ConsultState == 1 {
		return 1, errors.New("该项目已经结案了")
	}
	//结案此项目
	err = DB.Exec("UPDATE consult_situations SET consult_state = 1 WHERE recordid = ?", recordid).Error
	if err != nil {
		return 0, err
	}
	return 1, nil //已结案返回1，无异常
}

func (s *ConsultSituation) GetConsultSituation(num string) ([]ConsultSituation, error) {
	var ConsultSituation []ConsultSituation
	return ConsultSituation, DB.Where("student_num = ?", num).Find(&ConsultSituation).Error
}
